package com.zhc.dejingapi.utils;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author zhc
 * @date 2024年08月08日 9:12
 */
@Component
public class ObjectCopierUtils {

    public static void copyProperties(Object source, Object target) throws IllegalAccessException {
        if (source == null || target == null) {
            return;
        }
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        Field[] sourceFields = sourceClass.getDeclaredFields();
        for (Field sourceField : sourceFields) {
            sourceField.setAccessible(true);
            String fieldName = sourceField.getName();
            Object fieldValue = sourceField.get(source);

            try {
                Field targetField = targetClass.getDeclaredField(fieldName);
                targetField.setAccessible(true);
                targetField.set(target, fieldValue);
            } catch (NoSuchFieldException e) {
                // 目标对象中不存在该属性，忽略或者可以添加处理逻辑
            }
        }
    }

}
